// localStorage的封装

class Storages {
  /**
   * Creates an instance of Storage. 是否为持久缓存，为true调用localStorage否为sessionStorage
   * @param {boolean} [lasting=true]
   * @memberof Storage
   */
  constructor(lasting = true) {
    this.db = lasting ? localStorage : sessionStorage
  }

  set(name, value) {
    const str = JSON.stringify({ value })
    this.db.setItem(name, str)
  }

  get(name) {
    let value = this.db.getItem(name)
    if (!value) {
      return value
    }
    try {
      value = JSON.parse(value)
      return value.value
    } catch {
      return undefined
    }
  }

  delete(name) {
    this.db.removeItem(name)
  }

  deleteAll() {
    this.db.clear()
  }

  get length() {
    return this.db.length
  }
}

const storage = (...rest) => new Storages(...rest)

export default storage
